﻿using DuiBa;
using DuiBa.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Top.PointStore.Business;
using Top.PointStore.Business.Models;
using Top.Web.Api;
using Top.Web.Api.Filters;
using Top.Core;
using Top.PointStore.Business.Models.DuibaModel;
using Top.PointStore.Filters;
using Top.PointStore.Web.Core;
using System.Globalization;

namespace Top.PointStore.Web.Controllers
{
    public class DuiBaController : ApiBase
    {
        /// <summary>
        /// 兑吧积分商城
        /// </summary>
        /// <returns></returns>
        [Top.Web.Api.Filters.Login]
        public object GetURL()
        {

            T_PointMain_new t = PointManager.GetV2(User).Result;
            var rel= DuiBaSDK.GenerateURL(new GenerateURLRequest() { uid=t.F_UserToken, credits=t.F_PointBalance });
            return Redirect(rel,false);
            //return rel;
        }
        /// <summary>
        /// 兑吧-扣积分
        /// </summary>
        /// <returns></returns>
        [NoLogin][Idempotent]
        public async Task<object> MinusPoints()
        {
            Dictionary<string, string> requestDic;
            var rel = DuiBaSDK.MinusPoints(Context.Request.RequestUri.ToString(),out requestDic);
            if(rel.status=="ok")
            {
                var order = new DuibaOrder() { 
                    CreateTime = DateTime.Now, 
                    State = Top.PointStore.Business.DuibaOrderEnum.Waiting,
                    Description = requestDic["description"],
                    DuibaOrderNum = requestDic["orderNum"],
                    Other = requestDic["params"],
                    Credits = int.Parse(requestDic["credits"]),
                    UserToken = requestDic["uid"],
                    ProductType = requestDic["type"],
                };
                if(bool.Parse(requestDic["waitAudit"]))
                {
                    order.AuditStatus = DuibaOrderAuditStatus.Unreviewed;
                }
                else
                {
                    order.AuditStatus = DuibaOrderAuditStatus.NoAudit;
                    order.AuditTime = DateTime.Now;
                }
                try
                {
                    order.Kid = await DuibaOrderManager.MinusPoints(order);
                }
                catch
                {
                    order.Kid = -5;//参数错误
                }
                rel.bizId = DateTime.Now.ToString("yyyyMMddhhmmssfffffff") + order.Kid.ToString();
                var point=await PointManager.Get(requestDic["uid"]);
                //用户当前积分
                rel.credits = point.F_PointBalance;
                if(order.Kid<=0)
                {
                    rel.status = "fail";
                    rel.errorMessage = "order error "+order.Kid;
                }
            }
            return new DuibaJsonResult(rel);
        }
        /// <summary>
        /// 兑吧-订单状态更新
        /// </summary>
        /// <returns></returns>
        [NoLogin]
        public async Task<object> OrderRefreshState()
        {
            Dictionary<string, string> requestDic;
            if (DuiBaSDK.RequestSignVerify(Context.Request.RequestUri.ToString(), out requestDic) && requestDic.ContainsKey("orderNum") && requestDic.ContainsKey("success"))
            {
                var order = await DuibaOrderManager.Get(requestDic["orderNum"]);
                if(order!=null)
                {
                    if (bool.Parse(requestDic["success"]))
                    {
                        await DuibaOrderManager.UpdateState(requestDic["orderNum"], DuibaOrderEnum.Success);
                    }
                    else
                    {
                        await DuibaOrderManager.UpdateState(requestDic["orderNum"], DuibaOrderEnum.Fail);
                    }
                }
                return new StringResult("ok");
            }
            else
            {
                return new StringResult("fail");
            }
        }
        /// <summary>
        /// 兑吧-违规查询
        /// </summary>
        /// <returns></returns>
        [NoLogin]
        public async Task<object> ViolationApi()
        {
            string request = this.Url.ToString();
            Dictionary<string, string> paramDic = new Dictionary<string, string>();
            var verify = DuiBaSDK.RequestSignVerify(request, out paramDic);
            ViolationResponse response;
            if ((!verify)||(!paramDic.ContainsKey("uid")))
                response=new ViolationResponse{ success=false, message="unfind user"};
            else
                response = await DuibaOrderManager.GetCreditHistory(paramDic["uid"]);
            //var response = await DuibaBLL.GetCreditHistory(uid);
            return new DuibaJsonResult(response);
        }
        /// <summary>
        /// 订单审核
        /// </summary>
        /// <param name="duibaOrderNum"></param>
        /// <param name="IsApproved"></param>
        /// <returns></returns>
        [AdminLogin]
        public async Task<object> AuditOrder(string duibaOrderNum, bool IsApproved)
        {
            return await DuibaOrderManager.UpdateAuditStatus(duibaOrderNum, IsApproved ? DuibaOrderAuditStatus.Approved : DuibaOrderAuditStatus.NotApproved);
        }
        /// <summary>
        /// 获取订单列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [AdminLogin]
        public async Task<object> GetOrderList(int pageIndex = 1, int pageSize = 10, string orderNum = "", int state = -1, int city=-1,string type="",string start="",string end="",string phone="")
        {
            var orderList = await DuibaOrderManager.GetPage(Pager.Create(pageIndex,pageSize),orderNum,state,city,type,DateTimeEx.DefaultPrase(start),DateTimeEx.DefaultPrase(end),phone);
            foreach(var item in orderList.Items)
            {
                if(string.IsNullOrEmpty(item.UserName))
                {
                    item.UserName = item.AdminName ?? "";
                    item.Phone = item.AdminPhone ?? "";
                }
                if(string.IsNullOrEmpty(item.CityName))
                {
                    item.CityName = "杭州市 ";
                }
            }

            return orderList;
        }

        //导出excel
        [AdminLogin]
        public async Task<object> Export(string orderNum = "", int state = -1, int city = -1, string type = "", string start = "", string end = "", string phone = "")
        {
            return await DuibaOrderManager.Export(orderNum, state, city, type, DateTimeEx.DefaultPrase(start), DateTimeEx.DefaultPrase(end), phone);
        }
        /// <summary>
        /// 积分充值
        /// </summary>
        /// <returns></returns>
        [NoLogin]
        [Idempotent]
        public async Task<object> RechargePoint()
        {
            Dictionary<string, string> requestDic;
            if (DuiBaSDK.RequestSignVerify(Context.Request.RequestUri.ToString(), out requestDic) && requestDic.ContainsKey("uid") && requestDic.ContainsKey("params") && requestDic.ContainsKey("appKey"))
            {
                if(requestDic["appKey"]!=DuiBa.DuiBaSDK.AppKey)
                    return new DuibaJsonResult(new { status = "fail", errorMessage = "AppKey验证失败", supplierBizId = 0 });
                int orderId=0;
                if (!requestDic.ContainsKey("developBizId"))
                {
                    requestDic.Add("developBizId", DateTime.Now.ToString("yyyyMMddhhmmssfffffff") + "0");
                }
                if (requestDic["developBizId"].Length<18)
                {
                    requestDic["developBizId"] = DateTime.Now.ToString("yyyyMMddhhmmssfffffff")+"0";
                }
                if(int.TryParse(requestDic["developBizId"].Remove(0,17),out orderId))
                {

                    var rel = await DuibaOrderManager.RechargePoint(requestDic["uid"], requestDic["params"], orderId);
                    if(rel>0)
                    {
                        //用户当前积分
                        var point = await PointManager.Get(requestDic["uid"]);
                        return new DuibaJsonResult(new { status = "success", credits = point.F_PointBalance, supplierBizId = requestDic["developBizId"] });
                    }
                    else if(rel==-1)
                    {
                        return new DuibaJsonResult(new { status = "fail", errorMessage = "用户不存在", supplierBizId = requestDic["developBizId"] });
                    }
                    else if(rel==-2)
                    {
                        return new DuibaJsonResult(new { status = "fail", errorMessage = "积分规则不存在或未被启用", supplierBizId = requestDic["developBizId"] });
                    }
                    else
                    {
                        return new DuibaJsonResult(new { status = "fail", errorMessage = "未知", supplierBizId = rel });
                    }
                }
                else
                {
                    return new DuibaJsonResult(new { status = "fail", errorMessage = "订单号类型转换失败", supplierBizId = requestDic["developBizId"] });
                }
            }
            return new DuibaJsonResult(new { status = "fail", errorMessage = "签名验证失败", supplierBizId = 0 });
        }
    }
}